package org.meetunexpectedly.controller.middleground;

import org.meetunexpectedly.authority.Authority;
import org.meetunexpectedly.entity.middleground.Permission;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.holder.UserHolder;
import org.meetunexpectedly.service.middleground.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @Description: 权限控制器
 * @Author: pupil
 * @Date: 2024/09/03 下午 11:21
 */
@RestController
@RequestMapping("/authorize/permission")
public class PermissionController {

    @Autowired
    private PermissionService permissionService;


    /**
     * 初始化菜单
     *
     * @return
     */
    @GetMapping("/initMenu")
    public Map<String, Object> initMenu() {
        Map<String, Object> data = permissionService.initMenu(UserHolder.get());
        return data;
    }

    /**
     * 获取权限列表
     *
     * @return
     */
    @GetMapping("/list")
    @Authority("permission:list")
    public List<Permission> getPermissionList() {
        return permissionService.list(null);
    }

    /**
     * 查询权限树形结构
     *
     * @return
     */
    @GetMapping("/treeSelect")
    @Authority("permission:treeSelect")
    public List<Permission> treeSelect() {
        List<Permission> permissions = permissionService.treeSelect();
        return permissions;
    }

    /**
     * 添加权限
     *
     * @param permission 权限
     * @return
     */
    @PostMapping
    @Authority("permission:add")
    public Result addPermission(@RequestBody Permission permission) {
        permission.setIcon("fa " + permission.getIcon());
        permissionService.save(permission);

        return Result.ok();
    }

    /**
     * 修改权限
     *
     * @param permission 权限
     * @return
     */
    @PutMapping
    @Authority("permission:update")
    public Result updatePermission(@RequestBody Permission permission) {
        permission.setIcon("fa " + permission.getIcon());
        permissionService.updateById(permission);
        return Result.ok();
    }

    /**
     * 删除权限
     *
     * @param id 权限id
     * @return
     */
    @DeleteMapping("/{id}")
    @Authority("permission:delete")
    public Result deletePermission(@PathVariable Long id) {
        if (!permissionService.removePermission(id)) {
            return Result.error().message("删除失败");
        }
        return Result.ok().message("删除成功");
    }
}
